<?php
/**
 * Talents come from diligence, and knowledge is gained by accumulation.
 *
 * @author: 晋<657306123@qq.com>
 */

namespace app\admin\controller;

use app\admin\Controller;
use app\common\facade\View;
use think\exception\ValidateException;
use think\facade\Url;
use think\response\Redirect;
use Xin\Auth\LoginException;

class LoginController extends Controller{

	/**
	 * 登录
	 *
	 * @return mixed
	 */
	public function login(){
		if($this->user->getUserInfo(null, null, false)){
			$this->error('请不要重复登录！', 'index/index');
		}

		if($this->request->isPost()){
			$data = $this->validateLogin();

			try{
				$this->user->loginUsingPassword('username', $data['user'], $data['pwd']);
			}catch(LoginException $e){
				$this->error($e->getMessage());
			}

			$redirect = new Redirect;
			$redirect = $redirect->restore()->getData();
			if(empty($redirect)) $redirect = Url::build('index/index');

			$this->success('登录成功！', $redirect);
		}

		return View::fetch();
	}

	/**
	 * 登录验证
	 *
	 * @return array
	 */
	protected function validateLogin(){
		//验证验证码
		$verifyCode = $this->request->post("verify");
		if(!$this->request->isCli() && !captcha_check($verifyCode, "admin")){
			throw new ValidateException('验证码不正确！');
		}

		return $this->request->validate('user,pwd', [
			'rules' => [
				'user' => 'require|alphaDash',
				'pwd'  => 'require|alphaDash',
			],
			'field' => [
				'user' => '用户名',
				'pwd'  => '密码',
			],
		]);
	}

	/**
	 * 退出登录
	 */
	public function logout(){
		$this->user->logout();
		$this->redirect("login/login");
	}
}
